/* eslint-disable prefer-const */
import { ToolsService } from '@src/service/tools/tools.service';
import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { BaseService } from '@src/service/base/base.service';
import { InjectRepository } from '@nestjs/typeorm';
import { StructEntity } from '@src/entities/sys/struct.entity';
import { Repository } from 'typeorm';
import { CreateStructDto } from '@src/controllers/admin/system/struct/dto/index';
import { ObjectType } from '@src/types';
import { channelObject, sqlWhere } from '@src/utils';

@Injectable()
export class StructService extends BaseService {
  constructor(
    @InjectRepository(StructEntity)
    private readonly structRepository: Repository<StructEntity>,
    private readonly toolsService: ToolsService,
  ) {
    super(structRepository);
  }

  /**
   * @Description: 创建组织机构
   * @param {type}
   * @return:
   */
  public async create(createStructDto: CreateStructDto): Promise<any> {
    const { name, code } = createStructDto;
    if (name) {
      const result = await this.structRepository.count({ name });
      if (result) {
        throw new HttpException({ error: `你创建的name:${name},数据库已经存在,不能重复创建` }, HttpStatus.BAD_REQUEST);
      }
    }
    if (code) {
      const result = await this.structRepository.count({ code });
      if (result) {
        throw new HttpException({ error: `你创建的code:${code},数据库已经存在,不能重复创建` }, HttpStatus.BAD_REQUEST);
      }
    }
    const struct = await this.structRepository.create(createStructDto);
    return await this.structRepository.save(struct);
  }

  /**
   * @Description: 查询所有数据
   * @param {type}
   * @return:
   */
  public async findPage(options?: ObjectType): Promise<any> {
    const { name, code } = channelObject(options);

    const sql1 = 'select struct.* from struct';
    const sql2: string = sqlWhere({ code }, 'struct');
    let sql3 = '';
    if (name) {
      sql3 = (sql2 && sql2.trim()) ? ` and struct.name like '%${name}%'` : ` where struct.name like '%${name}%'`;
    }
    const sql4 = ` order by createdAt desc;`;
    const sql5 = sql1 + sql2 + sql3 + sql4;
    const data = await this.structRepository.query(sql5);

    return {
      result: this.toolsService.arrayToTree(data, 0),
    };
  }
}
